//
//  SYNetworking.m
//  CC-Store-iOS
//
//  Created by -- on 2018/4/12.
//  Copyright © 2018年 PayneCai. All rights reserved.
//

#import "SYNetworking.h"
#import "SYRequest.h"
#import "SYDataModel.h"
#import "AFNetworking.h"
#import "SYTools.h"

#import "HANavViewController.h"
#import "HALoginVC.h"
#import "AppDelegate.h"
#import "HAUserInfoVC.h"


@interface SYNetworking ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;
//请求任务池
@property (nonatomic, strong) NSMutableArray *requestTasksPools;

@end


@implementation SYNetworking

+ (SYNetworking *)shareSingle
{
    static dispatch_once_t onceToken;
    static SYNetworking *rq;
    dispatch_once(&onceToken, ^{
        rq = [[SYNetworking alloc] init];
    });
    return rq;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.manager= [AFHTTPSessionManager manager];
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",@"charset/UTF-8",@"image/jpeg", nil];
    }
    return self;
}

/**
 异步请求:以body方式,支持数组
 提供多个网络请求同时请求->完成多有请求后返回
 */
- (void)hgj_asynRequestWithArray:(NSArray <SYRequest *>*)requests responseBlock:(SYAsynResponseBlock)responseBlock {
    [self sy_Requests:requests isAsyn:YES response_Asyn:responseBlock response_Syn:nil];
}
//同步
- (void)hgj_synRequestWithArray:(NSArray <SYRequest *>*)requests responseBlock:(SYSynResponseBlock)responseBlock {
    [self sy_Requests:requests isAsyn:NO response_Asyn:nil response_Syn:responseBlock];
}

//异步网络请求
-(void)sy_Requests:(NSArray<SYRequest *> *)requests isAsyn:(BOOL)isAsyn response_Asyn:(SYAsynResponseBlock)response_Asyn response_Syn:(SYSynResponseBlock)response_Syn {
    [self orgVersionRequests:requests isAsyn:isAsyn response_Asyn:(SYAsynResponseBlock)response_Asyn response_Syn:(SYSynResponseBlock)response_Syn];
}


-(void)orgVersionRequests:(NSArray<SYRequest *> *)requests isAsyn:(BOOL)isAsyn response_Asyn:(SYAsynResponseBlock)response_Asyn response_Syn:(SYSynResponseBlock)response_Syn {
    
    //创建信号量
    dispatch_semaphore_t sem;
    if (!isAsyn) {
        sem = dispatch_semaphore_create(0);
        //解决死锁问题
        _manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    }
    
    //创建返回的数组
    NSMutableArray <SYDataModel *>*successArray = [NSMutableArray array];
    
    for (SYRequest *request in requests) {
        
        if (!request) {
            return;
        }
        
        NSString *url = [NSString stringWithFormat:@"%@api/%@",kHaBaseUrl,request.requestUrl];;

        //请求地址
        NSString *requestUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        //公共参数
        NSMutableDictionary *requestPrams = [NSMutableDictionary dictionaryWithDictionary:request.parms];

        //配置请求信息
        NSMutableURLRequest *req = [self sy_requestWithMethod:request.requestMethod Url:requestUrl Parms:requestPrams];
      
        [req setValue:HAUserDefaults.token forHTTPHeaderField:@"token"];

        req.timeoutInterval= 15;

        __block SYAsynResponseBlock res_asyn = response_Asyn;
        
        __block NSURLSessionTask *task = [self.manager dataTaskWithRequest:req uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            
            if (!error) {
                SYDataModel *responseModel = [SYDataModel mj_objectWithKeyValues:responseObject];
                responseModel.request = request;
                                

                //请求成功
                if (isAsyn) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //传输数据
                        if (res_asyn) {
                            res_asyn(responseModel);
                        }
                    });
                }else{
                    [successArray addObject:responseModel];
                }
                
            } else {
                //请求失败

                SYDataModel *responseModel = [[SYDataModel alloc]init];
                responseModel.request = request;
                responseModel.err = error;
                
                NSInteger code = 0;
                if ([[error.userInfo allKeys ]containsObject:AFNetworkingOperationFailingURLResponseErrorKey]) {
                    NSHTTPURLResponse *info = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
                    code = info.statusCode;
                }

                if (code == 401) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if ([HASingle single].onlyMenu) {
                            return;
                        }
                        
    //                    [HAHelper outUserInfo];
    //                    [HASingle single].isLogin = NO;
    //                    [AppDelegate single].window.rootViewController = [[HANavViewController alloc]initWithRootViewController:[HALoginVC new]];
    //
    //                    [[HASingle single].onlyMenu dismiss];
    //                    [HASingle single].onlyMenu = nil;

                        [HASingle single].onlyMenu = [[HATipsPopView alloc]initWithTitle:@"提示" content:@"您的登录已过期，请重新登录" left:@"确定" right:@""];
                        [[HASingle single].onlyMenu show];
                        [HASingle single].onlyMenu.XZYGTiShiLeftBlock = ^{
                            
                            [HAHelper outUserInfo];
                            [HASingle single].isLogin = NO;
                            [AppDelegate single].window.rootViewController = [[HANavViewController alloc]initWithRootViewController:[HALoginVC new]];
                            
                            [[HASingle single].onlyMenu dismiss];
                            [HASingle single].onlyMenu = nil;
                        };
                    });
                }else if (code == 402) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if ([HASingle single].onlyMenu) {
                            return;
                        }
                        [HASingle single].onlyMenu = [[HATipsPopView alloc]initWithTitle:@"提示" content:@"请完善资料" left:@"确定" right:@""];
                        [[HASingle single].onlyMenu show];
                        [HASingle single].onlyMenu.XZYGTiShiLeftBlock = ^{
                            
                            HAUserInfoVC *vc = [[HAUserInfoVC alloc]init];
                            vc.isFrist = YES;
                            [[HAHelper getCurrentVc].navigationController pushViewController:vc animated:YES];
                            
                            [[HASingle single].onlyMenu dismiss];
                            [HASingle single].onlyMenu = nil;
                        };
                    });

                }else {
                }
                
                if (isAsyn) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (res_asyn) {
                            res_asyn(responseModel);
                        }
                    });
                }else{
                    [successArray addObject:responseModel];
                }

            }
            //请求结束，移除task
            if ([self.requestTasksPools containsObject:task]) {
                [self.requestTasksPools removeObject:task];
            }
            if (!isAsyn) {
                dispatch_semaphore_signal(sem);
            }
        }];
        //
        [task resume];
        [self.requestTasksPools addObject:task];
        if (!isAsyn) {
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        }
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //传输数据
        if (response_Syn) {
            response_Syn(successArray);
        }
    });

}


//其他请求，需要完整的url
- (void)sy_requertWith:(NSString *)url  method:(NSString *)method parms: (id)parms success:(void(^)(id responseObject))success failure:(void(^)(NSError *errer))failure {
    
    NSString *requestUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //配置请求信息
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:requestUrl parameters:nil error:nil];
    request.timeoutInterval= 15;

    __block NSURLSessionTask *task = [self.manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            failure(error);
        }else{
            success(responseObject);
        }
    }];
    [task resume];
    
}

-(NSMutableURLRequest *)sy_requestWithMethod:(SYRequestMethod)method Url:(NSString *)url Parms:(id)parms {
    
    NSMutableURLRequest *req;
    NSString *methodString;
    //请求方式
    switch (method) {
        case SYRequestMethodGET:
            methodString = @"GET";
            req = [self ConfigureGetRequestMethod:methodString Url:url Parms:parms];
            break;
        case SYRequestMethodPOST:
            methodString = @"POST";
            req = [self ConfigureOtherRequestMethod:methodString Url:url Parms:parms];
            break;
        case SYRequestMethodPATCH:
            methodString = @"PATCH";
            req = [self ConfigureOtherRequestMethod:methodString Url:url Parms:parms];
            break;
        case SYRequestMethodDELETE:
            methodString = @"DELETE";
            req = [self ConfigureOtherRequestMethod:methodString Url:url Parms:parms];
            break;
            case SYRequestMethodPUT:
                methodString = @"PUT";
                req = [self ConfigureOtherRequestMethod:methodString Url:url Parms:parms];
                break;
        default:
            break;
    }
    
    return req;
    
}

-(NSMutableURLRequest *)ConfigureGetRequestMethod:(NSString *)method Url:(NSString *)url Parms:(id)parms {
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    request = [[AFHTTPRequestSerializer serializer] requestWithMethod:method URLString:url parameters:parms error:nil];
    request.timeoutInterval= 15;
    return request;
}

-(NSMutableURLRequest *)ConfigureOtherRequestMethod:(NSString *)method Url:(NSString *)url Parms:(id)parms {
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    request = [[AFHTTPRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil];

    NSString *param= [self requestBodyString:parms]; //[parms mj_JSONString];

    request.timeoutInterval= 30;

    NSData *postData = [param dataUsingEncoding:NSUTF8StringEncoding];
    // 设置body
    [request setHTTPBody:postData];
    
    return request;
}


-(NSString *)requestBodyString:(NSDictionary *)dict {
    
    NSString *string = @"";
    NSArray *keyArray = [dict allKeys];
    NSArray *valuesArray = [dict allValues];
    if (keyArray.count == valuesArray.count) {
        for (int i = 0; i < keyArray.count; i++) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",keyArray[i],valuesArray[i]];
            if (i == 0) {
                string = [NSString stringWithFormat:@"%@",str];
            }else{
                string = [NSString stringWithFormat:@"%@&%@",string,str];
            }
        }
    }
    
    return string;
}


-(NSMutableArray *)requestTasksPools
{
    if (!_requestTasksPools) {
        _requestTasksPools = [NSMutableArray array];
    }
    return _requestTasksPools;
}



@end
